<?php
class WebChatBase{
    private $appId = 'wx6e3a1edba84ac309';
//     private $appId = 'wx5a2ba62dcf70277c';
    private $scope_base = 'snsapi_base';
    private $scope_user_info = 'snsapi_userinfo';
    private $secret = '3ef2bf6e7fba7031525351f2e2b7840a';
//     private $secret = '5010de0e132d6d00c2bb43793fe4ee44';
    /**
     * 是否微信浏览器
     * @return boolean
     */

    public function is_weixin(){
        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            return true;
        }
        return false;
    }
    
    public function getOAuthCode($type='base' , $state = ''){
        $current_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $redirect_uri = urlencode($current_url);
        $appid=$this->appId;
        $response_type = 'code';
        $scope = $this->scope_base;
        if($type == 'userInfo'){
            $scope = $this->scope_user_info;
        }
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri='. $redirect_uri . '&response_type=' . $response_type . '&scope=' . $scope ;
        if($state != ''){
            $url .= '&state=' . $state ;
        }
        $url.= '#wechat_redirect';
        echo '<script type="text/javascript">';
        echo 'location.href = "' . $url . '";';
        echo '</script>';
        exit;
    }
    
    public function getOAuthAccessToken($code){
        $appid=$this->appId;
        $secret = $this->secret;
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code='. $code . '&grant_type=authorization_code';
        $resutl = json_decode(file_get_contents($url));       
        return $resutl;     
    }
    
    public function getAccessToken(){
        $accessToken = $this->getCache();
        if(!$accessToken){
            $appid=$this->appId;
            $secret = $this->secret;
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
            $resutl = array();
            for($i = 0 ; $i < 3 ; $i ++){
                $resutl = json_decode(file_get_contents($url),true);
                if(isset($resutl['access_token'])){
                    break;
                }
            }
            $accessToken = $resutl['access_token'];
            $this->setCache($accessToken);            
        }

        return $accessToken;
    }
    
    
    public function setCache($accessToken){
        $content = $accessToken . '&&' . date('Y-m-d H:i:s');
        $filename =  dirname(__FILE__) . '/../access_token.txt';
        file_put_contents($filename, $content);
    }
    
    public function getCache(){
       $accessToken = '';
       $filename =  dirname(__FILE__) . '/../access_token.txt';
       $content =  file_get_contents($filename);
       $tokenArr = explode('&&', $content);
       $tokenTime = strtotime($tokenArr[1]);
       $currentTime = time();
       if(($currentTime - $tokenTime) <= 5400){
           $accessToken = $tokenArr[0];
       }
       return  $accessToken;
    }
    
    public function jsapiTicket(){
        $jsapiTicket = '';
        $accessToken = $this->getAccessToken();
        if($accessToken){
            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $accessToken . '&type=jsapi';
            $resutl = json_decode(file_get_contents($url),true);
            $resutl = array();
            for($i = 0 ; $i < 3 ; $i ++){
                $resutl = json_decode(file_get_contents($url),true);
                if(isset($resutl['ticket'])){
                    break;
                }
            }
            $jsapiTicket = $resutl['ticket'];
        }
        return $jsapiTicket;
    }
    
    public function httpRequest($url , $data = array() , $method = 'get'){
        $result = array();
        if($method == 'post' && !empty($data)){
            $result = $this->_post($url, $data);
        }else{
            $result = $this->_get($url, $data);
        }
        return $result;
    }

    private function  _get($url , $data){
        $output = array();
        if(!empty($data)){
           $url .= '?' . http_build_query($data , 'dawangfu_');
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    private function _post($url , $data){
        $output = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}